
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

import '../../../../common/constants/app_constants.dart';
import '../../../../common/log/x_logger.dart';
import '../../../../common/widget/common.dart';
import '../../../../provider/global_provider.dart';
import '../../../../router/router_manager.dart';
import '../../../../theme/app_theme.dart';
import '../../../../utils/color_utils.dart';
import '../../../../utils/toast_utils.dart';
import '../../home/model/home_device_info_resp.dart';
import '../model/feedback_list_resp.dart';

/// 意见与反馈 页面
class FeedbackListPage extends ConsumerStatefulWidget {
  const FeedbackListPage({super.key});

  @override
  ConsumerState<FeedbackListPage> createState() => _FeedbackListPageState();
}

class _FeedbackListPageState extends ConsumerState<FeedbackListPage> {
  bool showLoading = true;
  bool showNodata = false;

  int pageNum = 1;
  List<FeedbackListData> dataList = <FeedbackListData>[];
  late EasyRefreshController _refreshController;

  _buildLoading() {
    return Center(
      child: CircularProgressIndicator(
        color: AppTheme.themeConfig.primaryColor,
      ),
    );
  }

  _buildList() {
    return ListView.builder(
      itemCount: dataList.length,
      itemBuilder: (context, index) {
        return _buildCell(index);
      },
    );
  }

  _toFeedbackDetail(int index) async {
    XLogger.info("反馈详情");
    final idstr = '${dataList[index].feedbackId}';
    await context.push('${RouterManager.feedbackDetail}?feedbackId=${Uri.encodeComponent(idstr)}');

    // context.push('/feedbackDetail?feedbackId=');
    XLogger.info('${RouterManager.feedbackDetail}?url=${Uri.encodeComponent(idstr)}');

  }

  _goFeedback() async{
    final result = await context.push(RouterManager.feedbackSubmit);
    if (result != null) {
      pageNum = 1;
      _fetchFeedList(true);

    }
    XLogger.info("去反馈");
  }

  _buildCell(int index) {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    FeedbackListData feedData = dataList[index];
    // 设备信息cell
    return GestureDetector(
      onTap: () async {
        // 跳转到反馈详情
        _toFeedbackDetail(index);
      },
      child: Stack(
        children: [
          Container(
            margin: const EdgeInsets.only(left: 20, right: 20, top: 20),
            padding: const EdgeInsets.only(
              left: 20,
              right: 20,
            ),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      // 名称
                      Text(
                        '${feedData.subject}',
                        style: TextStyle(
                          fontSize: 16,
                          color: AppTheme.themeConfig.primaryTextColor,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(
                        width: 10,
                      ),
                      Text(
                        '反馈内容：${feedData.content ?? ' '}',
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: 14,
                          color: AppTheme.themeConfig.secondaryTextColor,
                        ),
                      ),
                      if ((feedData.processing ?? "").isNotEmpty)
                      Text(
                        '处理结果：${feedData.processing ?? ' '}',
                        style: TextStyle(
                          fontSize: 14,
                          color: AppTheme.themeConfig.secondaryTextColor,
                        ),
                      ),

                    ],
                  ),
                ),
                // 处理状态
                _buildDeviceStatus(feedData.status ?? 0),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDeviceStatus(int status) {
    switch (status) {
      case 0:
        return _buildDeviceStatusView('待处理', '#909399');
      case 1:
        return _buildDeviceStatusView('已处理', '#19be6b');
      default:
        return _buildDeviceStatusView('未激活', '#c8c9cc');
    }
  }

  Widget _buildDeviceStatusView(String text, String color) {
    return Container(
      margin: const EdgeInsets.only(left: 10),
      padding: const EdgeInsets.only(left: 10, right: 10, top: 2, bottom: 2),
      decoration: BoxDecoration(
        color: ColorUtils.hexToColor(color),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Text(
        text,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 12,
        ),
      ),
    );
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 在build完成后回调
      // 获取设备列表
      _fetchFeedList(true);
    });
    super.initState();
    _refreshController = EasyRefreshController(
      controlFinishLoad: true,
      controlFinishRefresh: true,
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  _fetchFeedList(bool isRefresh) async {
    final deviceInfo = ref.watch(deviceInfoProvider);

    final queryParams = {
      'imei': deviceInfo.imei,
      'pageNum': pageNum,
      'pageSize': 10,
    };
    final res = await get<FeedbackListResp, FeedbackListResp>('$newBaseULr/feedback/list',
        queryParameters: queryParams, decodeType: FeedbackListResp());
    res.when(success: (FeedbackListResp resp) {
      if (resp.code == 200) {
        if (isRefresh) {
          dataList.clear();
          dataList.addAll(resp.data!);
          // 判断是否还有更多数据
          if (resp.data == null || resp.data!.isEmpty || resp.data!.length < 10) {
            _refreshController.finishLoad(IndicatorResult.noMore);
          } else {
            _refreshController.finishRefresh();
          }
          pageNum++;
        } else {
          if (resp.data == null || resp.data!.isEmpty) {
            _refreshController.finishLoad(IndicatorResult.noMore);
          } else {
            pageNum++;
            dataList.addAll(resp.data!);
            _refreshController.finishLoad();
          }
        }
        if (dataList.isEmpty) {
          showNodata = true;
        }
      } else {
        ToastUtils.showToast(resp.msg ?? '获取设备列表失败');
      }
      setState(() {
        showLoading = false;
      });
    }, failure: (String msg, int code) {
      XLogger.error('获取设备列表失败 code: $code msg: $msg');
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('反馈列表', style: TextStyle(fontSize: 18)),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.navBarColor,
        foregroundColor: AppTheme.themeConfig.primaryColor,
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Container(
            height: kToolbarHeight,
            padding: const EdgeInsets.only(top: 8),
            alignment: Alignment.center,
            child: const Text(' <返回',
                textAlign: TextAlign.center,
                maxLines: 1,
                style: TextStyle(color: Colors.black)),
          ),
        ),
      ),
      backgroundColor: AppTheme.themeConfig.navBarColor,
      body: Column(
        children: [
          if (dataList.length > 0)
          Expanded(child: EasyRefresh(
            controller: _refreshController,
            onRefresh: () async {
              pageNum = 1;
              await _fetchFeedList(true);
              _refreshController.finishRefresh();
            },
            onLoad: () async {
              await _fetchFeedList(false);
            },
            child: showLoading ? _buildLoading() : _buildList(),
            ),
          ),
          if (showNodata)
          const Expanded(child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image(
                image: AssetImage('assets/images/nodata.png'),
                width: 80,
              ),
              Text("暂无反馈数据"),
            ], )
          ),
          if (!showNodata)
            const Expanded(child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
              ], )
            ),
            GestureDetector(
            onTap: () {
              _goFeedback();
            },
            child: Container(
              alignment: Alignment.center,
              width: MediaQuery.of(context).size.width,
              margin:
              const EdgeInsets.only(left: 30, right: 30, top: 10, bottom: 16),
              padding: const EdgeInsets.symmetric(vertical: 8),
              decoration: BoxDecoration(
                  color: AppTheme.themeConfig.primaryColor,
                  borderRadius: BorderRadius.circular(20)),
              child: lpText(
                  "我要反馈",
                  color: Colors.white,
                  size: 16),
            ),
          )
        ],
      )
    );
  }
}
